package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.filter.Filters;
import com.otaliastudios.cameraview.gesture.Gesture;
import com.otaliastudios.cameraview.gesture.GestureAction;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.CameraTypeAdapter;
import flc.ast.adapter.ShotFilterAdapter;
import flc.ast.bean.MyCameraTypeBean;
import flc.ast.bean.MyShotFilterBean;
import flc.ast.databinding.ActivityCameraBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    private CameraTypeAdapter cameraTypeAdapter;
    private ShotFilterAdapter filterAdapter;
    private boolean isFlash = false;//判断是否打开闪光灯
    private int shotTime = 0;//拍摄延迟
    private int delayType = 0;
    private int number;//拍照倒计时
    private int typePos = 0, filterPos = 0;


    @Override
    protected int onCreate() {
        return R.layout.activity_camera;
    }

    @Override
    protected boolean isStatusBarTextDark() {
        return false;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.rvCameraTypeList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        cameraTypeAdapter = new CameraTypeAdapter();
        mDataBinding.rvCameraTypeList.setAdapter(cameraTypeAdapter);
        cameraTypeAdapter.setOnItemClickListener(this);
        mDataBinding.ivCameraDelay.setOnClickListener(this);
        mDataBinding.ivCameraTouch.setOnClickListener(this);
        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.ivCameraFilter.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.ivCameraFilterClose.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCameraDelay://延时拍摄
                openDelay();
                break;
            case R.id.ivCameraTouch://触碰拍摄
                openTouch();
                break;
            case R.id.ivCameraFlash://闪光灯
                openFlash();
                break;
            case R.id.ivCameraFilter://滤镜
                mDataBinding.llCameraBottomView.setVisibility(View.GONE);
                mDataBinding.llCameraFilterView.setVisibility(View.VISIBLE);
                break;
            case R.id.ivCameraStart://开始拍摄
                startShoot();
                break;
            case R.id.ivCameraReversal://镜头反转
                reversalLens();
                break;
            case R.id.ivCameraFilterClose://关闭滤镜
                mDataBinding.llCameraBottomView.setVisibility(View.VISIBLE);
                mDataBinding.llCameraFilterView.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == cameraTypeAdapter) {
            cameraTypeAdapter.getItem(typePos).setSelected(false);
            cameraTypeAdapter.notifyItemChanged(typePos);
            typePos = position;
            cameraTypeAdapter.getItem(position).setSelected(true);
            cameraTypeAdapter.notifyItemChanged(position);
            //设置样式
            mDataBinding.ivCameraSelImg.setImageResource(cameraTypeAdapter.getItem(position).getImg());
        } else if (adapter == filterAdapter) {
            filterAdapter.getItem(filterPos).setSelect(false);
            filterAdapter.notifyItemChanged(filterPos);
            filterPos = position;
            filterAdapter.getItem(position).setSelect(true);
            filterAdapter.notifyItemChanged(position);
            //设置滤镜
            mDataBinding.cameraView.setFilter(filterAdapter.getItem(position).getFilter());
        }
    }

    @Override
    protected void initData() {
        //样式数据
        List<MyCameraTypeBean> list = new ArrayList<>();
        list.add(new MyCameraTypeBean(R.drawable.aimg_xj1, R.drawable.aimage_xj1));
        list.add(new MyCameraTypeBean(R.drawable.aimg_xj2, R.drawable.aimage_xj2));
        list.add(new MyCameraTypeBean(R.drawable.aimg_xj3, R.drawable.aimage_xj3));
        list.add(new MyCameraTypeBean(R.drawable.aimg_xj4, R.drawable.aimage_xj4));
        list.add(new MyCameraTypeBean(R.drawable.aimg_xj5, R.drawable.aimage_xj5));
        list.add(new MyCameraTypeBean(R.drawable.aimg_xj6, R.drawable.aimage_xj6));
        list.add(new MyCameraTypeBean(R.drawable.aimg_xj7, R.drawable.aimage_xj7));
        list.add(new MyCameraTypeBean(R.drawable.aimg_xj8, R.drawable.aimage_xj8));
        list.get(0).setSelected(true);
        mDataBinding.ivCameraSelImg.setImageResource(list.get(0).getImg());
        cameraTypeAdapter.setList(list);
        getPermission();
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
                //准备滤镜数据
                initFilter();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                showDialog(getString(R.string.save_picture_ing));
                int picWidth = result.getSize().getWidth();
                int picHeight = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (picWidth * picHeight > screenWidth * screenHeight) {
                    picWidth = screenWidth;
                    picHeight = screenHeight;
                }
                result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        //放入控件并保存
                        mDataBinding.ivCameraShootImg.setImageBitmap(bitmap);
                        mDataBinding.ivCameraShootImg.setVisibility(View.VISIBLE);
                        RxUtil.create(new RxUtil.Callback<Boolean>() {

                            @Override
                            public void doBackground(ObservableEmitter<Boolean> emitter) {
                                Bitmap saveBitmap = ImageUtils.view2Bitmap(mDataBinding.rlCameraSaveView);
                                ImageUtils.save2Album(saveBitmap, Bitmap.CompressFormat.PNG);
                                emitter.onNext(true);
                            }

                            @Override
                            public void accept(Boolean isSave) {
                                dismissDialog();
                                mDataBinding.ivCameraShootImg.setVisibility(View.GONE);
                                ToastUtils.showShort(R.string.save_suc_to_album);
                                mDataBinding.ivCameraStart.setEnabled(true);
                            }
                        });
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    //初始化滤镜
    private void initFilter() {
        List<MyShotFilterBean> mFilterList = new ArrayList<>();//滤镜集合
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_1, Filters.values()[0].newInstance(), true));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_2, Filters.values()[1].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_3, Filters.values()[2].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_4, Filters.values()[3].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_5, Filters.values()[4].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_6, Filters.values()[5].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_7, Filters.values()[6].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_8, Filters.values()[7].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_9, Filters.values()[8].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_10, Filters.values()[9].newInstance(), false));
        mFilterList.add(new MyShotFilterBean(R.drawable.filter_12, Filters.values()[11].newInstance(), false));

        mDataBinding.rvFilterList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        filterAdapter = new ShotFilterAdapter();
        mDataBinding.rvFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
        filterAdapter.setList(mFilterList);
    }

    //打开延时拍摄
    private void openDelay() {
        if (delayType == 0) {
            delayType = 1;
            shotTime = 7000;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.aicon_shijian);
        } else if (delayType == 1) {
            delayType = 0;
            shotTime = 0;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.aicon_shijian2);
        }
    }

    //打开触屏拍摄
    private void openTouch() {
        GestureAction action = mDataBinding.cameraView.getGestureAction(Gesture.TAP);
        if (action == GestureAction.NONE) {
            mDataBinding.ivCameraTouch.setImageResource(R.drawable.aicon_cpp);
            mDataBinding.cameraView.mapGesture(Gesture.TAP, GestureAction.TAKE_PICTURE_SNAPSHOT);
        } else {
            mDataBinding.ivCameraTouch.setImageResource(R.drawable.aicon_cp2);
            mDataBinding.cameraView.clearGesture(Gesture.TAP);
        }
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.aicon_sgd2);
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.aicon_sgd);
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    //开始拍摄
    private void startShoot() {
        mDataBinding.ivCameraStart.setEnabled(false);//点击按钮不可点击 避免重复点击
        if (mDataBinding.cameraView.isTakingPicture()) return;
        //加个拍照延迟
        if (shotTime > 0) {
            delayNumber();//倒计时
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mDataBinding.cameraView.takePictureSnapshot();
            }
        }, shotTime);
    }

    //倒计时
    private void delayNumber() {
        number = shotTime / 1000;
        new CountDownTimer(shotTime, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mDataBinding.tvCameraTipText.setVisibility(View.VISIBLE);
                //millisUntilFinished / 1000 会有不可描述的问题
                mDataBinding.tvCameraTipText.setText("" + number--);
            }

            @Override
            public void onFinish() {
                mDataBinding.tvCameraTipText.setVisibility(View.GONE);
            }
        }.start();
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

}